package baiqitun.stupro.common.workflow.util;

import baiqitun.stupro.common.exception.enums.support.NotFoundExceptionEnum;
import baiqitun.stupro.common.workflow.enums.ProcessVariableEnum;
import baiqitun.stupro.common.exception.support.NotFoundException;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;

/**
 * TaskService的封装
 * @author kedaji
 */
@Service
public class TaskUtil {
    @Autowired
    private TaskService taskService;

    /**
     * 获取某个任务
     * @param processDefinitionKey 流程定义Key
     * @param taskId 任务id
     * @return 任务
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public Task getTaskById(@NotBlank(message = "流程定义key不能为空") String processDefinitionKey, String taskId){
        return taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                .taskId(taskId)
                .singleResult();
    }

    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public Task getTaskByOwner(@NotBlank(message = "流程定义key不能为空") String processDefinitionKey, String owner){
        return taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                .taskOwner(owner)
                .orderByTaskCreateTime()
                .singleResult();
    }

    /**
     * 获取由流程实例的任务
     * @param processDefinitionKey 流程定义Key
     * @param processInstanceId 流程实例id
     */
    public Task getTaskByProcessInstanceId(@NotBlank(message = "流程定义key不能为空") String processDefinitionKey, String processInstanceId){
        return taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                .processInstanceId(processInstanceId)
                .singleResult();
    }

    /**
     * 设置任务的发起人
     * @param processDefinitionKey 流程定义key
     * @param taskId 任务id
     * @param owner 任务发起人id
     */
    @Transactional(rollbackFor = Exception.class)
    public void setOwnerForTask(String processDefinitionKey, String taskId, String owner){
        checkExisted(processDefinitionKey, taskId);
        taskService.setOwner(taskId, owner);
    }

    /**
     * 获取所有等待assignee处理的任务
     * @param processDefinitionKey 流程定义Key
     * @param assignee 任务处理人
     * @return 任务列表
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public List<Task> listTaskByAssignee(String processDefinitionKey, String assignee){
        return taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                .taskAssignee(assignee)
                .orderByTaskCreateTime().orderByExecutionId().desc()
                .list();
    }

    /**
     * 分页查询所有等待assignee处理的任务
     * @param processDefinitionKey 流程定义Key
     * @param assignee 任务处理人
     * @param pageNo 页码
     * @param pageSize 每页查询几条记录
     * @return 任务列表
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public Page<Task> pageTaskByAssignee(String processDefinitionKey, String assignee, int pageNo, int pageSize){
        List<Task> records = taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                .taskAssignee(assignee)
                .orderByTaskCreateTime().orderByExecutionId().desc()
                .listPage(pageNo, pageSize);
        long count = taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                .taskAssignee(assignee).count();

        return assemblePage(records, pageNo, pageSize, count);
    }

    /**
     * 组装分页对象
     * @param records 查询到的记录
     * @param pageNo 页码
     * @param pageSize 每页数据的容量
     * @param total 总记录数
     * @param <E> 任意对象
     * @return 分页对象
     */
    private <E> Page<E> assemblePage(List<E> records, int pageNo, int pageSize, long total){
        Page<E> page = new Page<>();
        page.setRecords(records);
        page.setCurrent(pageNo);
        page.setSize(pageSize);
        page.setTotal(total);
        page.setSize((total + pageSize - 1) / pageSize);
        return page;
    }

    /**
     * 获取所有由owner发起的任务
     * @param processDefinitionKey 流程定义Key
     * @param owner 任务发起人
     * @return 任务列表
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public List<Task> listTaskByOwner(String processDefinitionKey, String owner){
        return taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                .taskOwner(owner)
                .orderByTaskCreateTime().orderByExecutionId().desc()
                .list();
    }

    /**
     * 分页查询所有由owner发起的任务
     * @param processDefinitionKey 流程定义Key
     * @param owner 任务发起人
     * @param pageNo 页码
     * @param pageSize 每页查询几条记录
     * @return 任务列表
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public IPage<Task> pageTaskByOwner(String processDefinitionKey, String owner, int pageNo, int pageSize){
        List<Task> tasks = taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                .taskOwner(owner)
                .orderByTaskCreateTime().orderByExecutionId().desc()
                .listPage(pageNo, pageSize);
        long total = taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                .taskOwner(owner).count();
        return assemblePage(tasks, pageNo, pageSize, total);
    }

    /**
     * 获取由owner发起的任务的个数
     * @param processDefinitionKey 流程定义Key
     * @param owner 任务发起人
     * @return 任务个数
     */
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public long countTaskByOwner(String processDefinitionKey, String owner){
        return taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                .taskOwner(owner)
                .count();
    }

    /**
     * 处理任务
     * @param processDefinitionKey 流程定义Key
     * @param taskId 要处理的任务id
     */
    @Transactional(rollbackFor = Exception.class)
    public void handleTask(String processDefinitionKey,String taskId, String result){
        HashMap<String, Object> variables = new HashMap<>(1);
        variables.put(ProcessVariableEnum.RESULT.name(),result);
        checkExisted(processDefinitionKey, taskId);
        taskService.complete(taskId, variables);
    }

    /**
     * 检查指定的任务是否存在
     * @param processDefinitionKey 流程定义key
     * @param taskId 任务id
     */
    public void checkExisted(String processDefinitionKey, String taskId){
        Task task = getTaskById(processDefinitionKey, taskId);
        if (task == null){
            throw new NotFoundException(NotFoundExceptionEnum.TASK_NOT_FOUND);
        }
    }

    /**
     * 检查指定的任务是否存在
     * @param processDefinitionKey 流程定义key
     * @param taskId 任务id
     * @param owner 任务发起人
     */
    public void checkOwnerHasTask(String processDefinitionKey, String taskId, String owner){
        checkExisted(processDefinitionKey, taskId);
        long count = taskService.createTaskQuery()
                .processDefinitionKey(processDefinitionKey)
                .taskOwner(owner)
                .taskId(taskId).count();
        if (count == 0){
            throw new NotFoundException(NotFoundExceptionEnum.TASK_NOT_FOUND).put("taskId", taskId).put("owner", owner);
        }
    }

    /**
     * 获取存在的/未处理的任务
     * @param processDefinitionKey 流程定义key
     * @param taskId 任务id
     * @return 任务
     */
    public Task getExistedTask(String processDefinitionKey, String taskId){
        Task task = getTaskById(processDefinitionKey, taskId);
        if (task == null){
            throw new NotFoundException(NotFoundExceptionEnum.TASK_NOT_FOUND).put("taskId", taskId);
        }
        return task;
    }
}
